package com.linln.admin.pcs.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.config.SmsUtils;
import com.linln.admin.config.ToInterFaceToolConfig;
import com.linln.admin.pcs.service.RsaService;
import com.linln.admin.pcs.service.TemplateMessageService;
import com.linln.admin.pcs.service.WechatPayRefundService;
import com.linln.admin.pcs.service.WxJsPayService;
import com.linln.admin.rsa.ToInterfaceTool;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.DateUtils;
import com.linln.common.utils.ResultVoUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import com.linln.modules.system.service.OrderAmountsService;
import com.linln.modules.system.service.OrderPortersService;
import com.linln.modules.system.service.PorterService;
import com.linln.modules.system.service.SmsLogService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Example;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Component
@EnableScheduling
public class TimedTask {

    private final static Logger logger = LoggerFactory.getLogger(TimedTask.class);

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private PorterService porterService;

    @Autowired
    private OrderPortersService orderPortersService;

    @Autowired
    private PorterRepository porterRepository;

    @Autowired
    private OrderAmountsService orderAmountsService;

    @Autowired
    private MsgRepository msgRepository;

    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private TaskMsgRepository taskMsgRepository;

    @Autowired
    private WechatPayRefundService wechatPayRefundService;

    @Autowired
    private PayRecordRepository payRecordRepository;

    @Autowired
    private CompanyParamRepository companyParamRepository;

    @Autowired
    private WxJsPayService wxJsPayService;

    @Autowired
    private RsaService rsaService;

    @Autowired
    private PatientAdmissionRepository patientAdmissionRepository;

    @Autowired
    private PatientRepository patientRepository;

    @Autowired
    private TemplateMessageService templateMessageService;

    @Autowired
    private SmsLogService smsLogService;

    @Autowired
    private SmsLogRepository smsLogRepository;

    /**
     * 当订单超时没有接单时候 自动取消订单
     */
    @Scheduled(cron = "40 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void updateOrder() throws Exception {
        logger.error("当订单超时没有接单时候 自动取消订单");
        String dates = DateUtils.getDates();
        List<Order> orderList = orderRepository.selectOrderList(dates);
        logger.error("当订单超时没有接单时候 自动取消订单："+orderList);
        for (Order order : orderList) {
            int orderStatus = order.getOrderStatus();
            if (orderStatus==0){
                order.setOrderStatus(-1);
                order.setEndTime(dates);
                String msg = "订单超时没有接单，自动取消";
                order.setRemark(msg);
                //将退还费用
                Double total = order.getTotal();
                Double balance = order.getBalance();
                Double refund = balance-total;
                if (refund>0){
                    PayParam payParam =  new PayParam();
                    payParam.setOutTradeNo(order.getSn());
                    payParam.setTotalFee(String.valueOf(balance));
                    payParam.setRefundFee(String.valueOf(refund));
                    payParam.setType(1);
                    Map<String, String> msgMap = wechatPayRefundService.handleRefund(payParam);
                    String code = msgMap.get("code");
                    orderRepository.save(order);
                    //更新记录
                    orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),-1,"",dates,1,order.getType());
                }else{
                    orderRepository.save(order);
                    //更新记录
                    orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),-1,"",dates,1,order.getType());
                }
                try {
                    Patient patient = patientRepository.findById(order.getPatientId()).get();
                    String contents = "订单超时没有接单，自动取消";
                    if (StringUtils.isNotEmpty(patient.getPhone())){
                        String ss = IDCardEncryptor.aesDecrypt(patient.getPhone());
                        String resp = SmsUtils.sendSms(ss, contents);
                        logger.error("接单超时消息发送结果："+resp);
                        smsLogService.insert(order.getSn(),patient.getPhone(),4,3,patient.getId(),contents,resp);
                    }else{
                        smsLogService.insert(order.getSn(),patient.getPhone(),4,3,patient.getId(),contents,"发送失败,手机号为空");
                    }
                } catch (Exception e) {
                    logger.error("自动取消消息发送失败"+e.getMessage());
                }
            }

        }
    }


    /**
     * 每分钟执行一次  30分钟后，修改订单状态为已取消
     */
    @Scheduled(cron = "20 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void cancel() throws Exception {
        logger.error("修改订单状态为已取消");
        Order order1 = new Order();
        order1.setStatus((byte) 1);
        order1.setOrderStatus(3);
        order1.setType(1);
        Example<Order> example = Example.of(order1);
        List<Order> orderList = orderRepository.findAll(example);
        if (orderList.size()>0){
            logger.error("修改订单状态列表"+orderList);
        }
        //当前时间
        String time = DateUtils.getTempTime();
        String[] nowMin = time.split(":");
        for (Order order : orderList) {
            String concludeTime = order.getConcludeTime();
            if (StringUtils.isNotEmpty(concludeTime)){
                String[] conTime = concludeTime.split(":");
                if (nowMin.length>1&&conTime.length>1){
                    String h1 = nowMin[0];
                    String h2 = conTime[0];
                    if (h1.equals(h2)){
                        String s1 = nowMin[1];
                        String s2 = conTime[1];
                        if (Integer.parseInt(s1)-Integer.parseInt(s2)==30) {
                            order.setOrderStatus(-1);
                            order.setRemark("订单超时，自动取消");
                            orderRepository.save(order);
                            //更新护工表限制服务人数
                            porterService.updatePorter(0,order.getPorterId(),order.getNumberLimit(),order.getId(),2);
                            //更新记录
                            orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),-1,"",DateUtils.getDates(),1,order.getType());

                            Map<String, String> data = new HashMap<>();
                            data.put("thing1", order.getProjectTitle());
                            data.put("phrase5", "超时未缴费，自动取消");
                            try {
                                Patient patient = patientRepository.findById(order.getPatientId()).get();
                                String resp = templateMessageService.sendTemplateMessage(patient.getOpenid(),"PH8ffR37gOytIEJIt-hOic7WHTnc8M-O1y8Mp2RUooU","",data);
                                logger.error("超时未缴费消息发送结果："+resp);
                            } catch (WxErrorException e) {
                                logger.error("消息发送失败"+e.getMessage());
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 1月1号0点执行一次  更新护工年龄
     */
    @Scheduled(cron = "0 0 0 1 1 ?")
    @Transactional(rollbackFor = Exception.class)
    public void updatePorterAge() throws Exception {
        logger.error("更新护工年龄");
        Porter porter1 = new Porter();
        porter1.setStatus((byte) 1);
        Example<Porter> example = Example.of(porter1);
        List<Porter> porterList = porterRepository.findAll(example);
        String year = DateUtils.getYear();
        for (Porter porter : porterList) {
            String cardNo = IDCardEncryptor.aesDecrypt(porter.getCardNo());
            if (cardNo.length()>10){
                String substring = cardNo.substring(6,10);
                porter.setAge(Integer.parseInt(year)-Integer.parseInt(substring));
            }
        }
        porterRepository.saveAll(porterList);
    }

    /**
     * 每分钟执行一次  按照选择的阶段时间自动扣款
     */
    @Scheduled(cron = "30 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void settleOrder() throws Exception {
        logger.error("按照选择的阶段时间自动扣款");
        Order order1 = new Order();
        order1.setPayStatus((byte) 1);
        order1.setBeforeStatus((byte) 1);
        order1.setStatus((byte) 1);
        order1.setType(1);
        order1.setOrderStatus(2);
        Example<Order> example = Example.of(order1);
        List<Order> orderList = orderRepository.findAll(example);
        if (orderList.size()>0){
            logger.error("自动扣款列表"+orderList);
        }
        //当前天
        String nowTime = DateUtils.getDate();
        Date date = DateUtils.parseStrToDate(DateUtils.YYYY_MM_DD, nowTime);
        //当前时间戳
        long time = date.getTime();
        String tempTime = DateUtils.getTempTime();
        String[] nowMin = tempTime.split(" ");
        //存储需要扣费的订单
        List<Order> tempOrderList = new ArrayList<>();
        for (Order order : orderList) {
            if (null!=order.getBalance()&&null!=order.getTotal()&&null!=order.getPrice()){
                Double balance = order.getBalance();
                Double total = order.getTotal();
                Double price = order.getPrice();

                int stageType = order.getStageType();
                //1 实时结算 2 延时结算
                int settlementType = order.getSettlementType();
                if (settlementType==1) {

                    double totalTemp = 0.00;

                    //获取下一次的扣除费用 判断费用是否足够 如果余额不足 通知患者
                    double nextTotal = 0.00;

                    //下一次需要缴纳的费用
                    double restNextMoney = 0.00;
                    if (stageType==1){
                        BigDecimal bd = new BigDecimal(price);
                        BigDecimal td = new BigDecimal(total);
                        BigDecimal rest = td.add(bd);
                        BigDecimal dca = rest.setScale(2, RoundingMode.HALF_UP);
                        totalTemp = dca.doubleValue();

                        //计算下一次的费用
                        BigDecimal nextOne = rest.add(bd);
                        BigDecimal nextTwo = nextOne.setScale(2, RoundingMode.HALF_UP);
                        nextTotal = nextTwo.doubleValue();

                        restNextMoney = bd.doubleValue();
                    }else{
                        BigDecimal bd = new BigDecimal(price);
                        BigDecimal result = bd.multiply(new BigDecimal(order.getHourNum()));
                        BigDecimal td = new BigDecimal(total);
                        BigDecimal rest = td.add(result);
                        BigDecimal dca = rest.setScale(2, RoundingMode.HALF_UP);
                        totalTemp = dca.doubleValue();

                        //计算下一次的费用
                        BigDecimal nextOne = rest.add(result);
                        BigDecimal nextTwo = nextOne.setScale(2, RoundingMode.HALF_UP);
                        nextTotal = nextTwo.doubleValue();

                        restNextMoney = result.doubleValue();
                    }

                    //判断余额是否充足
                    int comparison = balance.compareTo(totalTemp);
                    if (comparison>=0){
                        updateMoney(order,time,nowMin,tempOrderList,1);
                        //判断余额是否支持下一次扣款 不支持则发送消息通知患者
                        int comparisons = balance.compareTo(nextTotal);
                        if (comparisons<0){
                            String nowDay = DateUtils.getDate();
                            List<SmsLog> smsLogs = smsLogRepository.selectSmsLogList(order.getSn(), nowDay);
                            if (smsLogs.size()>0){
                                try {
                                    Patient patient = patientRepository.findById(order.getPatientId()).get();
                                    String contents = "您的【一对一陪护】订单，余额不足请及时缴费。";
                                    if (StringUtils.isNotEmpty(patient.getPhone())){
                                        String ss = IDCardEncryptor.aesDecrypt(patient.getPhone());
                                        String resp = SmsUtils.sendSms(ss, contents);
                                        logger.error("及时缴费消息发送："+resp);
                                        smsLogService.insert(order.getSn(),patient.getPhone(),3,3,patient.getId(),contents,resp);
                                    }else{
                                        smsLogService.insert(order.getSn(),patient.getPhone(),3,3,patient.getId(),contents,"发送失败,手机号为空");
                                    }
                                } catch (Exception e) {
                                    logger.error("及时缴费消息发送失败："+e.getMessage());
                                }
                            }
                        }
                    }else{
                        //更新订单状态为终止
                        updateMoney(order,time,nowMin,tempOrderList,2);
                    }
                }else{
                    updateMoney(order,time,nowMin,tempOrderList,1);
                }
            }
        }
        if (tempOrderList.size()>0){
            orderRepository.saveAll(tempOrderList);
        }
    }


    /**
     * 每分钟执行一次  检查退款订单是否退款成功
     */
    @Scheduled(cron = "10 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void checkRefundOrder() throws Exception {
        logger.error("检查退款订单是否退款成功");
        PayRecord payRecord = new PayRecord();
        payRecord.setOutStatus(1);
        payRecord.setBackStatus(2);
        Example<PayRecord> example = Example.of(payRecord);
        List<PayRecord> payRecordList = payRecordRepository.findAll(example);
        if (payRecordList.size()>0){
            //记录退款成功的订单
            List<PayRecord> tempPayRecordList = new ArrayList<>();
            //记录回调信息
            List<TaskMsg> taskMsgList = new ArrayList<>();
            logger.error("退款中的订单**********"+payRecordList);
            for (PayRecord record : payRecordList){
                QuerySpec querySpec1 = QuerySpec.matching();
                querySpec1.withMatcherValue("companyId", QuerySpec.EQUAL, String.valueOf(record.getCompanyId()));
                querySpec1.withMatcherValue("status", QuerySpec.EQUAL, "1");
                List<CompanyParam> companyParamList = companyParamRepository.findAll(QuerySpec.of(querySpec1));
                if (companyParamList.size()>0){
                    CompanyParam companyParam = companyParamList.get(0);
                    if (ObjectUtils.isNotEmpty(companyParam.getApiKey())&&ObjectUtils.isNotEmpty(companyParam.getKeyPath())
                            &&ObjectUtils.isNotEmpty(companyParam.getMchId())){
                        String orderNo = record.getOrderNo();
                        Order order = new Order();
                        order.setSn(orderNo);
                        Order order1 = orderRepository.findOne(Example.of(order)).get();

                        //子订单号 也就是退款订单号
                        String orderChildNo = record.getOrderChildNo();

                        PayParam payParam = new PayParam();
                        payParam.setApiKey(companyParam.getApiKey());
                        payParam.setKeyPath(companyParam.getKeyPath());
                        payParam.setMchId(companyParam.getMchId());
                        payParam.setOutRefundNo(record.getOutRefundNo());
                        payParam.setOutTradeNo(orderChildNo);
                        Map<String, String> refundResult = wxJsPayService.queryRefundOrder(payParam);

                        TaskMsg taskMsg = new TaskMsg();
                        taskMsg.setOutRefundNo(record.getOutRefundNo());
                        Example<TaskMsg> example1 = Example.of(taskMsg);
                        //查询是否有记录
                        List<TaskMsg> msgList = taskMsgRepository.findAll(example1);
                        TaskMsg taskMsg2 = new TaskMsg();
                        taskMsg2.setPatientName(record.getPatientName());
                        taskMsg2.setOrderNo(orderNo);
                        taskMsg2.setType(record.getType());
                        taskMsg2.setOutRefundNo(record.getOutRefundNo());
                        taskMsg2.setOutRefundFee(record.getOutRefundFee());
                        taskMsg2.setMsg(refundResult.get("msg"));
                        taskMsg2.setStatus((byte) 1);
                        String code = refundResult.get("code");
                        if (code.equals("200")){
                            record.setBackStatus(1);
                            tempPayRecordList.add(record);
                            if (msgList.size()>0){
                                TaskMsg taskMsg1 = msgList.get(0);
                                taskMsg1.setMsg(refundResult.get("msg"));
                                taskMsg1.setBackStatus(1);
                                taskMsgList.add(taskMsg1);
                            }else{
                                taskMsg2.setBackStatus(1);
                                taskMsgList.add(taskMsg2);
                            }
                            //更新订单信息
                            changeOrderStatus(order1,"1");
                        } else if (code.equals("300")) {
                            if (msgList.size()<=0){
                                taskMsg2.setBackStatus(2);
                                taskMsgList.add(taskMsg2);
                            }
                        }else if (code.equals("400")) {
                            record.setBackStatus(0);
                            record.setRemark(refundResult.get("msg"));
                            tempPayRecordList.add(record);
                            if (msgList.size()>0){
                                TaskMsg taskMsg1 = msgList.get(0);
                                taskMsg1.setMsg(refundResult.get("msg"));
                                taskMsg1.setBackStatus(0);
                                taskMsgList.add(taskMsg1);
                            }else{
                                taskMsg2.setBackStatus(0);
                                taskMsgList.add(taskMsg2);
                            }
                            //更新订单信息
                            order1.setRefundRemark(refundResult.get("msg"));
                            changeOrderStatus(order1,"2");
                        }else if (code.equals("500")) {
                            if (msgList.size()<=0){
                                taskMsg2.setBackStatus(2);
                                taskMsgList.add(taskMsg2);
                            }
                        }
                    }
                }
            }
            logger.error("记录退款结果的订单**********"+tempPayRecordList);
            logger.error("退款订单信息**********"+taskMsgList);
            if (tempPayRecordList.size()>0){
                payRecordRepository.saveAll(tempPayRecordList);
            }
            if (taskMsgList.size()>0){
                taskMsgRepository.saveAll(taskMsgList);
            }
        }
    }

    /**
     * 获取患者住院信息  判断患者是否出院
     */
    @Scheduled(cron = "0 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void updatePatientAdmissionInfo() throws Exception {
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("admissionStatus", QuerySpec.EQUAL, "1")
                .withMatcherValue("status", QuerySpec.EQUAL, "1");
        List<PatientAdmission> patientAdmissionList = patientAdmissionRepository.findAll(QuerySpec.of(querySpec));
        if (patientAdmissionList.size()>0){
            List<Long> padIds = patientAdmissionList.stream().map(PatientAdmission::getId).collect(Collectors.toList());
            List<Object> padIds1 = new LinkedList<>();
            for (Long padId : padIds) {
                padIds1.add(padId);
            }
            QuerySpec querySpec1 = QuerySpec.matching();
            querySpec1.withMatcherValue("status", QuerySpec.EQUAL, "1");
            querySpec1.withMatcherValue("admissionStatus", QuerySpec.EQUAL, "1");
            List<Object> statusList = new LinkedList<>();
            statusList.add(0);
            statusList.add(1);
            statusList.add(2);
            statusList.add(3);
            statusList.add(4);
            querySpec1.withMatcherIn("orderStatus", statusList);
            querySpec1.withMatcherIn("patientAdmissionId", padIds1);
            List<Order> orderList = orderRepository.findAll(QuerySpec.of(querySpec1));
            List<PatientAdmission> tempPatientAdmissionList = new LinkedList<>();
            for (PatientAdmission patientAdmission : patientAdmissionList){
                String body = rsaService.getPatientCyAdmissionInfo(patientAdmission);
                if (StringUtils.isNotEmpty(body)){
                    JSONObject jsonObject = JSONObject.parseObject(body);
                    logger.error("定时患者住院信息:"+jsonObject);
                    if (ObjectUtils.isNotEmpty(jsonObject)){
                        if (jsonObject.containsKey("success")) {
                            boolean ss = jsonObject.getBoolean("success");
                            if (ss){
                                if (jsonObject.containsKey("data")) {
                                    JSONArray ary = jsonObject.getJSONArray("data");
                                    if (ary.size()>0){
                                        Object obj = ary.get(0);
                                        JSONObject data = (JSONObject) obj;
                                        int patInStatus = data.getInteger("patInStatus");
                                        //患者状态 1正常在院、101医生下出院医嘱、102护士出院医嘱校对完成、103申请出院、104结算出院
                                        int patStatus = data.getInteger("patStatus");
                                        logger.error("定时患者住院信息状态:"+patInStatus);
                                        //患者住院状态 1在院、2出院、3取消入院
                                        if (patInStatus == 2 || patStatus==103 || patStatus == 104) {
                                            patientAdmission.setAdmissionStatus((byte) 2);
                                            patientAdmission.setDischargeTime(data.getString("patOutTime"));
                                            patientAdmissionRepository.save(patientAdmission);
                                            for (Order order : orderList){
                                                if (Objects.equals(order.getPatientAdmissionId(), patientAdmission.getId())){
                                                    updateAdmissionOrderStatus(order);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    }

    private void changeOrderStatus(Order order,String status) {
        Byte refundStatus = order.getRefundStatus();
        if (status.equals("1")){
            //1 陪护 2 陪诊 3 陪检
            int type = order.getType();
            String msg = "";
            switch (type){
                case 1:msg = "陪护";break;
                case 2:msg = "陪诊";break;
                case 3:msg = "陪检";break;
            }
            //判断是陪护还是陪诊陪检  如果是陪护则预缴费用
            if (type == 1) {
                //新增金额变动表
                orderAmountsService.updateOrderAmounts(order,"患者"+msg+"订单退款",3);
            } else {
                //新增金额变动表
                orderAmountsService.updateOrderAmounts(order,"患者"+msg+"订单退款",3);
            }

            if (refundStatus == 1 || refundStatus == 3){
                //退款成功
                order.setRefundStatus((byte) 2);
                order.setRefundRemark("退款成功");
                orderRepository.save(order);
            }

        }else{
            if (refundStatus == 1){
                order.setRefundStatus((byte) 3);
                orderRepository.save(order);
            }

        }
    }


    /**
     * 更新订单金额和订单状态
     * @param order
     * @param time
     * @param nowMin
     * @param tempOrderList
     * @param status  1、余额充足 2、余额不足
     */
    private void updateMoney(Order order,long time,String[] nowMin,List<Order> tempOrderList,int status) throws Exception {
        logger.error("更新费用:"+order);
        //1按阶段选择 2按小时选择
        int stageType = order.getStageType();
        //开始天
        String startDay = order.getStartDay();
        if (StringUtils.isNotEmpty(startDay)){
            Date date1 = DateUtils.parseStrToDate(DateUtils.YYYY_MM_DD, startDay);
            long time1 = date1.getTime();
            //开始时间点
            String timeStart = order.getTimeStart();
            if (time>time1){
                if (StringUtils.isNotEmpty(timeStart)&&nowMin.length>1){
                    //当前时间点
                    String nowStart = nowMin[1];
                    String[] split1 = timeStart.split(":");
                    String[] split2 = nowStart.split(":");

                    int h1 = Integer.parseInt(split1[0]);//开始时间的小时
                    int h2 = Integer.parseInt(split2[0]);//当前时间的小时

                    int m1 = Integer.parseInt(split1[1]);
                    int m2 = Integer.parseInt(split2[1]);
                    //判断是否当前时间点是否等于扣费开始时间点
                    if (h1==h2&&m1==m2){
                        if (status==1){
                            //消费一次金额变动
                            orderAmountsService.updateOrderAmounts(order,"患者费用扣除",1);
                            //扣除费用
                            double total = 0.00;
                            Double price = order.getPrice();
                            Double total1 = order.getTotal();

                            if (stageType==1){
                                BigDecimal bd = new BigDecimal(price);
                                BigDecimal td = new BigDecimal(total1);
                                BigDecimal rest = td.add(bd);
                                BigDecimal dca = rest.setScale(2, RoundingMode.HALF_UP);
                                total = dca.doubleValue();
                            }else{
                                BigDecimal bd = new BigDecimal(price);
                                BigDecimal result = bd.multiply(new BigDecimal(order.getHourNum()));
                                BigDecimal td = new BigDecimal(total1);
                                BigDecimal rest = td.add(result);
                                BigDecimal dca = rest.setScale(2, RoundingMode.HALF_UP);
                                total = dca.doubleValue();
                            }
                            order.setTotal(total);
                            order.setNum(order.getNum()+1);
                            tempOrderList.add(order);
                        }else{
                            //更新订单状态为终止
                            updateOrderStatus(order);
                        }
                    }
                }
            }
        }
    }

/*    *//**
     * 暂时废弃
     */
   /* private void updateHourMoney(Order order,String[] nowMin,String timeStart,List<Order> tempOrderList,int status,int flag) throws Exception {
        int hourNum = order.getHourNum();
        //结束时间
        String timeEndTemp = order.getTimeEndTemp();
        if (StringUtils.isNotEmpty(timeEndTemp)){
            //当前时间点
            String nowStart = nowMin[1];
            String[] split1 = timeStart.split(":");
            String[] split2 = nowStart.split(":");
            String[] split3 = timeEndTemp.split(":");
            //判断当前时间是否在时间段内
            if (split1.length>1&&split2.length>1&&split3.length>1){
                int h1 = Integer.parseInt(split1[0]);//开始时间的小时
                int h2 = Integer.parseInt(split2[0]);//当前时间的小时
                int h3 = Integer.parseInt(split3[0]);//结束时间的小时

                int m1 = Integer.parseInt(split1[1]);
                int m2 = Integer.parseInt(split2[1]);
                int m3 = Integer.parseInt(split3[1]);
                //判断分钟是否相等
                if (m1==m2){
                    if (h3<=24){
                        if (flag==1){
                            if (h2>=h1&&h2<h3){
                                if (status==1){
                                    //需要扣费
                                    //消费一次金额变动
                                    orderAmountsService.updateOrderAmounts(order,"患者费用扣除",1);
                                    //扣除费用
                                    order.setTotal(order.getTotal()+order.getPrice());
                                    order.setNum(order.getNum()+1);
                                    tempOrderList.add(order);
                                }else{
                                    //更新订单状态为终止
                                    updateOrderStatus(order);
                                }
                            }
                        }else{
                            if (h2>h1&&h2<h3){
                                if (status==1){
                                    //需要扣费
                                    //消费一次金额变动
                                    orderAmountsService.updateOrderAmounts(order,"患者费用扣除",1);
                                    //扣除费用
                                    order.setTotal(order.getTotal()+order.getPrice());
                                    order.setNum(order.getNum()+1);
                                    tempOrderList.add(order);
                                }else{
                                    //更新订单状态为终止
                                    updateOrderStatus(order);
                                }
                            }
                        }

                    } else {
                        if (flag==1){
                            if (h2>=h1){
                                if (status==1){
                                    //需要扣费
                                    //消费一次金额变动
                                    orderAmountsService.updateOrderAmounts(order,"患者费用扣除",1);
                                    //扣除费用
                                    order.setTotal(order.getTotal()+order.getPrice());
                                    order.setNum(order.getNum()+1);
                                    tempOrderList.add(order);
                                }else{
                                    //更新订单状态为终止
                                    updateOrderStatus(order);
                                }
                            }else{
                                int tempH2 = h2+24;
                                if (tempH2>h1&&tempH2<h3){
                                    if (status==1){
                                        //需要扣费
                                        //消费一次金额变动
                                        orderAmountsService.updateOrderAmounts(order,"患者费用扣除",1);
                                        //扣除费用
                                        order.setTotal(order.getTotal()+order.getPrice());
                                        order.setNum(order.getNum()+1);
                                        tempOrderList.add(order);
                                    }else{
                                        //更新订单状态为终止
                                        updateOrderStatus(order);
                                    }
                                }
                            }
                        }else{
                            if (h2>h1){
                                if (status==1){
                                    //需要扣费
                                    //消费一次金额变动
                                    orderAmountsService.updateOrderAmounts(order,"患者费用扣除",1);
                                    //扣除费用
                                    order.setTotal(order.getTotal()+order.getPrice());
                                    order.setNum(order.getNum()+1);
                                    tempOrderList.add(order);
                                }else{
                                    //更新订单状态为终止
                                    updateOrderStatus(order);
                                }
                            }else{
                                int tempH2 = h2+24;
                                if (tempH2>h1&&tempH2<h3){
                                    if (status==1){
                                        //需要扣费
                                        //消费一次金额变动
                                        orderAmountsService.updateOrderAmounts(order,"患者费用扣除",1);
                                        //扣除费用
                                        order.setTotal(order.getTotal()+order.getPrice());
                                        order.setNum(order.getNum()+1);
                                        tempOrderList.add(order);
                                    }else{
                                        //更新订单状态为终止
                                        updateOrderStatus(order);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }*/

    private void updateOrderStatus(Order order) throws Exception {
        int orderStatus = order.getOrderStatus();
        //判断订单是否在服务中
        if (orderStatus==2){
            int type = order.getType();
            if (type==1){
                //将退还费用
                Double total = order.getTotal();
                Double balance = order.getBalance();
                Double refund = balance-total;
                if (refund>0){
                    PayParam payParam =  new PayParam();
                    payParam.setOutTradeNo(order.getSn());
                    payParam.setTotalFee(String.valueOf(balance));
                    payParam.setRefundFee(String.valueOf(refund));
                    payParam.setType(5);
                    Map<String, String> msgMap = wechatPayRefundService.handleRefund(payParam);
                    String code = msgMap.get("code");
                    String msg = msgMap.get("msg");
                    updateMsg(order);
                }else{
                    updateMsg(order);
                }
            }
        }
    }

    private void updateMsg(Order order){
        //新增余额不足消息通知
        Msg msg = new Msg();
        msg.setPatientId(order.getPatientId());
        msg.setType((byte) 1);
        String msgs = order.getProjectTitle();
        msg.setSn(order.getSn());
        msg.setContent("您好!您陪护订单的["+msgs+"]因余额不足,已终止服务,若继续服务请重新下单!");
        msgRepository.save(msg);
        //更新护工表限制服务人数
        porterService.updatePorter(0,order.getPorterId(),order.getNumberLimit(),order.getId(),2);
        //更新订单状态为完成
        order.setOrderStatus(5);
        order.setEndTime(DateUtils.getDates());
        orderRepository.save(order);
        //更新记录
        orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),2,"",DateUtils.getDates(),1,order.getType());
    }


    private void updateAdmissionOrderStatus(Order order) throws Exception {
        //1 陪护 2 陪诊 3 陪检
        int type = order.getType();
        if (type==1){
            //1 实时结算 2 延时结算
            int settlementType = order.getSettlementType();
            //将退还费用
            Double total = order.getTotal();
            Double balance = order.getBalance();
            Double refund = balance-total;
            if (refund>0&&settlementType==1){
                PayParam payParam =  new PayParam();
                payParam.setOutTradeNo(order.getSn());
                payParam.setTotalFee(String.valueOf(balance));
                payParam.setRefundFee(String.valueOf(refund));
                payParam.setType(3);
                Map<String, String> msgMap = wechatPayRefundService.handleRefund(payParam);
                String code = msgMap.get("code");
                String msg = msgMap.get("msg");
                //更新订单状态
                order.setOrderStatus(5);
                order.setEndTime(DateUtils.getDates());
                //更新护工表限制服务人数
                porterService.updatePorter(0,order.getPorterId(),order.getNumberLimit(),order.getId(),2);
                orderRepository.save(order);
                //更新记录
                orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),2,"",DateUtils.getDates(),1,order.getType());
            }else{
                //判断订单是否在服务中
                int orderStatus = order.getOrderStatus();
                if (orderStatus==2){
                    //更新订单状态
                    order.setOrderStatus(5);
                    order.setEndTime(DateUtils.getDates());
                    //更新护工表限制服务人数
                    porterService.updatePorter(0,order.getPorterId(),order.getNumberLimit(),order.getId(),2);
                    orderRepository.save(order);
                    //更新记录
                    orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),2,"",DateUtils.getDates(),1,order.getType());
                }else{
                    //更新护工表限制服务人数
                    porterService.updatePorter(0,order.getPorterId(),order.getNumberLimit(),order.getId(),2);
                    order.setOrderStatus(-1);
                    order.setRemark("患者出院自动取消订单");
                    orderRepository.save(order);
                    //更新记录
                    orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),-1,"",DateUtils.getDates(),1,order.getType());
                }

            }
        }else{
            //将退还费用
            /*Double total = order.getTotal();
            Double balance = order.getBalance();
            Double refund = balance-total;
            if (refund>0){
                PayParam payParam =  new PayParam();
                payParam.setOutTradeNo(order.getSn());
                payParam.setTotalFee(String.valueOf(balance));
                payParam.setRefundFee(String.valueOf(refund));
                payParam.setType(4);
                Map<String, String> msgMap = wechatPayRefundService.handleRefund(payParam);
                String code = msgMap.get("code");
                String msg = msgMap.get("msg");
                order.setOrderStatus(5);
                orderRepository.save(order);
                //更新记录
                orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),2,"",DateUtils.getDates(),1,order.getType());
            }else{
                order.setOrderStatus(5);
                orderRepository.save(order);
                //更新记录
                orderPortersService.updatePorterOrder(order.getId(),order.getPorterId(),0L,order.getCompanyId(),2,"",DateUtils.getDates(),1,order.getType());
            }*/
        }
    }
}
